//
//  AppDelegate.swift
//  FlyBirdPushQQ
//
//  Created by 郑东喜 on 2017/3/6.
//  Copyright © 2017年 郑东喜. All rights reserved.
//  信鸽推送

import UIKit
import UserNotifications


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
    
    var window: UIWindow?
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        
        let setPush = XGSetting()
        setPush.enableDebug(true)
        
        
        XGPush .startApp(2200253203, appKey: "I9E11TY7QU3B")
        
        self.registerAPNs(application)
        
        XGPush.isPush { (isPushOn) in
            print("\((#file as NSString).lastPathComponent):(\(#line))\n",isPushOn ? "on" : "off")
        }
        
        if launchOptions != nil {
            
            XGPush.handleLaunching(launchOptions!, successCallback: {
                print("\((#file as NSString).lastPathComponent):(\(#line))\n")
            }) {
                print("\((#file as NSString).lastPathComponent):(\(#line))\n")
            }
        }
        
        return true
        
    }
}


extension AppDelegate {
    // 向APNs注册，获取deviceToken用于推送
    func registerAPNs(_ application: UIApplication) {
        if #available(iOS 10, *) {
            // iOS 10+
            let center = UNUserNotificationCenter.current()
            // 创建category，并注册到通知中心
            createCustomNotificationCategory()
            center.delegate = self
            // 请求推送权限
            center.requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
                if (granted) {
                    // User authored notification
                    print("User authored notification.")
                    // 向APNs注册，获取deviceToken
                    application.registerForRemoteNotifications()
                } else {
                    // User denied notification
                    print("User denied notification.")
                }
            })
        } else if #available(iOS 8, *) {
            // iOS 8+
            application.registerUserNotificationSettings(UIUserNotificationSettings.init(types: [.alert, .badge, .sound], categories: nil))
            application.registerForRemoteNotifications()
        } else {
            // < iOS 8
            application.registerForRemoteNotifications(matching: [.alert,.badge,.sound])
        }
    }
    
    // 创建自定义category，并注册到通知中心
    @available(iOS 10, *)
    func createCustomNotificationCategory() {
        let action1 = UNNotificationAction.init(identifier: "action1", title: "test1", options: [])
        let action2 = UNNotificationAction.init(identifier: "action2", title: "test2", options: [])
        let category = UNNotificationCategory.init(identifier: "test_category", actions: [action1, action2], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
        UNUserNotificationCenter.current().setNotificationCategories([category])
    }
}

// MARK:- 适配ios10
extension AppDelegate {
    
    // App处于前台时收到通知(iOS 10+)
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Receive a notification in foreground.")
        
        // 通知弹出，且带有声音、内容和角标
        completionHandler([.alert, .badge, .sound])
    }
    
    // 触发通知动作时回调，比如点击、删除通知和点击自定义action(iOS 10+)
    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        XGPush.handleReceiveNotification(response.notification.request.content.userInfo , successCallback: {
            
            print("\((#file as NSString).lastPathComponent):(\(#line))\n","Handle receive success")
        }) {
            print("\((#file as NSString).lastPathComponent):(\(#line))\n","Handle receive error")
        }
        
        completionHandler()
    }
}

extension AppDelegate {
    
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("\((#file as NSString).lastPathComponent):(\(#line))\n","receive slient Notification")
        
        print("\((#file as NSString).lastPathComponent):(\(#line))\n",userInfo)
        print("\((#file as NSString).lastPathComponent):(\(#line))\n",userInfo["xg"])
        
        XGPush.handleReceiveNotification(userInfo, successCallback: {
            print("\((#file as NSString).lastPathComponent):(\(#line))\n","Handle receive success")
        }) {
            print("\((#file as NSString).lastPathComponent):(\(#line))\n","Handle receive error")
        }
        
        completionHandler(.newData)
    }
    
    
    // APNs注册成功
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("Get deviceToken from APNs success.")
        
        let deviceTokenStr = XGPush.registerDevice(deviceToken, successCallback: {
            print("\((#file as NSString).lastPathComponent):(\(#line))\n","rigister push success")
            print("\((#file as NSString).lastPathComponent):(\(#line))\n")
        }) {
            print("\((#file as NSString).lastPathComponent):(\(#line))\n","rigister push error")
        }
        
        print("\((#file as NSString).lastPathComponent):(\(#line))\n",deviceTokenStr)
        
        
    }
    
    // APNs注册失败
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Get deviceToken from APNs failed, error: \(error).")
    }
    
    // 禁止横屏
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait;
    }
    
}
